#include <boost/asio.hpp>
#include <tbb/tbb_thread.h>

#include "SyncConnection.h"
#include "Auxiliary.h"
#include "Request.h"

using namespace boost::asio;
using namespace std;
using namespace tbb;


SyncConnection::SyncConnection(ServerInfo &info, size_t socketCount)
{
	// Creating new connections.
	for (size_t i = 0; i < socketCount; i++)
	{
		new tbb_thread(start, info);
	}

	// Sleeping.
	while (true)
	{
		this_tbb_thread::sleep(tick_count::interval_t(1000000.0));
	}
}

void SyncConnection::start(ServerInfo &info)
{
	io_service io_service;

	while (true)
	{
		try
		{
			bool isFailed = false;
			Stats::GetRef()->RegisterStartedRequest();

			// Initing connection.
			ip::tcp::socket s(io_service);
			boost::system::error_code error = error::host_not_found;
			s.connect(ip::tcp::endpoint(info.GetIpAddress(), info.GetPort()), error);

			if (error)
			{
				throw runtime_error(error.message().c_str());
			}

			// Sending data.
			tick_count t_start = tick_count::now();
			s.send(buffer(request), 0, error);
			isFailed = isFailed || error;

			// Receiving data.
			boost::array<unsigned char, 16000> buf;
			s.receive(buffer(buf), 0, error);
			isFailed = isFailed || error;
			tick_count t_end = tick_count::now();
			s.close();
			Stats::GetRef()->RegisterRequest(!isFailed, t_end - t_start);
		}
		catch (exception &ex)
		{
			// Doing nothing
		}
	}
}